package br.com.werp.regras.contabilidade.migracao;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStreamReader;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.swing.JFileChooser;


/**
 * @author Sobreira
 * Criado em 27/02/2007
 */
public class MigracaoPlanoContas {
    public static File carregarArquivo(String texto) {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.showDialog(null, texto);

        return fileChooser.getSelectedFile();
    }

    public static void main(String[] args) throws SQLException, Exception {
        Class.forName("org.postgresql.Driver");

        Connection con =
            DriverManager.getConnection("jdbc:postgresql://192.168.1.5:5432/UniDados",
                "postgres", "database");
        BufferedReader reader =
            new BufferedReader(new InputStreamReader(
                    new FileInputStream(carregarArquivo("Plano de contas")),"ISO8859-1"));
        String linha = reader.readLine();
        System.out.println(con.isClosed());
        con.setAutoCommit(false);
        int contador = 0;
        try {
            while (linha != null) {
                PreparedStatement statement = con.prepareStatement(linha);
                statement.executeUpdate(linha);
                System.out.println(++contador + linha);
                linha = reader.readLine();
            }            
        } catch (Exception e) {
            System.out.println(e.getMessage());
            System.out.println(linha);
            con.rollback();
            con.close();
            System.exit(0);
        }

        con.commit();
        con.close();
    }
}
